package com.bosssoft.boss_exam_db.service.busines.impl;

import com.bosssoft.boss_exam_db.entity.Company;
import com.bosssoft.boss_exam_db.entity.ExamExamPaper;
import com.bosssoft.boss_exam_db.entity.ExamPaper;
import com.bosssoft.boss_exam_db.entity.ExamPaperQuestion;
import com.bosssoft.boss_exam_db.mapper.ExamPaperMapper;
import com.bosssoft.boss_exam_db.mapper.ExamPaperQuestionMapper;
import com.bosssoft.boss_exam_db.mapper.QuestionMapper;
import com.bosssoft.boss_exam_db.model.DTO.RandomPaperDTO;
import com.bosssoft.boss_exam_db.model.vo.ExamPaperIsSubmitVO;
import com.bosssoft.boss_exam_db.model.vo.ExamPaperQuestionVO;
import com.bosssoft.boss_exam_db.model.vo.ExamPaperVO;
import com.bosssoft.boss_exam_db.service.base.impl.BaseServiceImpl;
import com.bosssoft.boss_exam_db.service.busines.ExamExamPaperService;
import com.bosssoft.boss_exam_db.service.busines.ExamPaperQuestionService;
import com.bosssoft.boss_exam_db.service.busines.ExamPaperService;
import com.bosssoft.boss_exam_db.util.MySqlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExamPaperServiceImpl extends BaseServiceImpl<ExamPaper> implements ExamPaperService {

    //注入ExamPaperMapper
    @Autowired
    private ExamPaperMapper examPaperMapper;

    //注入ExamPaperQuestionMapper
    @Autowired
    private ExamPaperQuestionMapper examPaperQuestionMapper;

    //注入QuestionMapper
    @Autowired
    private QuestionMapper questionMapper;

    // 注入试卷服务
    @Autowired
    private ExamPaperService examPaperService;

    // 注入试卷问题服务
    @Autowired
    private ExamPaperQuestionService examPaperQuestionService;

    // 注入考试试卷服务
    @Autowired
    private ExamExamPaperService examExamPaperService;


    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/3/17
     * @Description 根据试卷名称模糊查询、岗位ID、是否开发标志进行多条件查询
     * @Param [company, examPaperName, jobId, openFlag, page, limit, sort, order]
     * @Return com.github.pagehelper.PageInfo<com.bosssoft.boss_exam_db.entity.ExamPaper>
     * @Exception //无
     * @since JDK 1.8
     **/
    @Override
    public PageInfo<ExamPaperIsSubmitVO> queryByCondition(Company company, String examPaperName, String jobId, Integer openFlag, Integer page, Integer limit, String sort, String order) {
        Example example = new Example(ExamPaper.class);
        Example.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(company.getId())){
            criteria.andEqualTo("companyId", company.getId());
        }
        if(!StringUtils.isEmpty(examPaperName)){
            criteria .andLike("name", MySqlUtil.cloumLike(examPaperName));
        }
        if(!StringUtils.isEmpty(jobId)){
            criteria   .andEqualTo("jobId", jobId);
        }
        if(openFlag!=null){
            criteria   .andEqualTo("openFlag", openFlag);
        }
        criteria.andEqualTo("deleted", false);
        PageHelper.startPage(page, limit).setOrderBy(sort + " " + order);
        List<ExamPaper> examPapers = this.examPaperMapper.selectByExample(example);

        List<ExamPaperIsSubmitVO> examPaperIsSubmitVOS = examPapers.stream().map(examPaper -> {
            Boolean isSubmit = examPaperService.checkIsSummitQuestion(company.getId(), examPaper.getId());
            ExamPaperIsSubmitVO examPaperIsSubmitVO = new ExamPaperIsSubmitVO();
            BeanUtils.copyProperties(examPaper,examPaperIsSubmitVO);
            examPaperIsSubmitVO.setIsSubmit(isSubmit);
            return examPaperIsSubmitVO;
        }).collect(Collectors.toList());
        PageInfo<ExamPaperIsSubmitVO> examPaperIsSubmitVOPageInfo = new PageInfo(examPaperIsSubmitVOS);
        return  examPaperIsSubmitVOPageInfo;
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/4/8
     * @Description 根据试卷ID查询所有的试卷题目
     * @Param [id] 试卷ID
     * @Return java.util.List<com.bosssoft.boss_exam_db.model.vo.ExamPaperVO>
     * @Exception
     * @since JDK 1.8
     **/
    @Override
    public List<ExamPaperVO> selectAllQuestion(String id) {
        ExamPaper examPaper = examPaperMapper.selectByPrimaryKey(id);
        if(examPaper==null||examPaper.getDeleted()==false){
            return null;
        }
        Example example = new Example(ExamPaperQuestion.class);
        Example.Criteria criteria = example.createCriteria();
        if(id!=null){
            criteria.andEqualTo("examPaperId",id);
        }
        criteria  .andEqualTo("deleted", false);
        List<ExamPaperQuestion> examPaperQuestions = examPaperQuestionMapper.selectByExample(example);
//        examPaperQuestions.stream().forEach(examPaperQuestion -> {
//            Question question=questionMapper.selectByPrimaryKey(examPaperQuestion.getQuestionId());
//            return question;
//        });
//        ExamPaperVO examPaperVO = new ExamPaperVO(examPaper,);
//        return examPaperQuestions;
        return null;
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/4/8
     * @Description 检查是否提交过试卷
     * @Param [compamyId, examPaperId] 供公司ID、试卷ID
     * @Return java.lang.Boolean
     * @Exception
     * @since JDK 1.8
     **/
    @Override
    public Boolean checkIsSummitQuestion(String compamyId, String examPaperId) {
        Example example = new Example(ExamPaperQuestion.class);
        Example.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(compamyId)){
            criteria.andEqualTo("companyId",compamyId);
        }
        if(!StringUtils.isEmpty(examPaperId)){
            criteria.andEqualTo("examPaperId",examPaperId);
        }
        criteria.andEqualTo("deleted",false);
        List<ExamPaperQuestion> examPaperQuestions = this.examPaperQuestionMapper.selectByExample(example);
        if(examPaperQuestions!=null&&examPaperQuestions.size()>0){
            return true;
        }
        return false;
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/4/8
     * @Description 删除试卷及试卷下的题目
     * @Param [examPaper] 试卷
     * @Return java.lang.Boolean
     * @Exception
     * @since JDK 1.8
     **/
    @Override
    public Boolean deleteForCascade(ExamPaper examPaper) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        int examPaperDeleteResult = examPaperService.deleteForLogic(examPaper);
        ExamPaperQuestion examPaperQuestion = new ExamPaperQuestion();
        examPaperQuestion.setExamPaperId(examPaper.getId());
        examPaperQuestion.setDeleted(true);
        Example example = new Example(ExamPaperQuestion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("examPaperId",examPaper.getId());
        int examPaperQuestionDeleteResult = examPaperQuestionMapper.updateByExampleSelective(examPaperQuestion, example);
        if(examPaperDeleteResult>0&&examPaperQuestionDeleteResult>0){
            return true;
        }
        return false;
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/3/25
     * @Description 管理员查询试卷
     * @Param [companyId, examPaperId, questionTypeMaps]当前用户所属公司ID  试卷ID 问题类型字典
     * @Return java.util.List<com.bosssoft.boss_exam_db.model.DTO.RandomPaperDTO.QuestionTypeOrderNum>
     * @Exception //无
     * @since JDK 1.8
     **/
    @Override
    public List<RandomPaperDTO.QuestionTypeOrderNum> queryExamPaperQuestionDetail(String companyId, String examPaperId,List<Map<String, Object>> questionTypeMaps) {
        //包含了试卷实体和问题实体
        List<ExamPaperQuestionVO> examPaperQuestionVOS =this.examPaperQuestionMapper.queryExamPaperQuestionDetail(companyId,examPaperId);
        Map<Object, List<ExamPaperQuestionVO>> map = examPaperQuestionVOS.stream().collect(Collectors.groupingBy(examPaperQuestionVO -> {
                    return examPaperQuestionVO.getQuestion().getQuestionType().getId();
                }));
        // map包含的数据格式为 key 为题型ID  value为该题型的ExamPaperQuestionVO
        System.out.println(map);
        List<RandomPaperDTO.QuestionTypeOrderNum> questionTypeOrderNums= new ArrayList<RandomPaperDTO.QuestionTypeOrderNum>();
        for(Map.Entry entry : map.entrySet()){
            RandomPaperDTO.QuestionTypeOrderNum questionTypeOrderNum = new RandomPaperDTO.QuestionTypeOrderNum();
            String questionId = (String)entry.getKey();
            Map<String, Object> questionTypeMap = questionTypeMaps.stream().filter(item -> item.get("id").equals(questionId)).collect(Collectors.toList()).get(0);
            questionTypeOrderNum.setQuestionTypeId((String)questionTypeMap.get("id"));
            questionTypeOrderNum.setOrderNum((Integer) questionTypeMap.get("orderNum"));
            questionTypeOrderNum.setQuestionTypeName((String)questionTypeMap.get("name"));
            List<ExamPaperQuestionVO> currentQuestionTypeVOs = map.get(questionId);
            // 查询出QuestionAndTypeVO列表
//            List<QuestionAndTypeVO> questionAndTypeVOList = currentQuestionTypeVOs.stream().map(currentQuestionTypeVO -> currentQuestionTypeVO.getQuestion()).collect(Collectors.toList());
            // 将问题封装到questionTypeOrderNum中
            questionTypeOrderNum.setQuestionAndTypeVOList(currentQuestionTypeVOs);
            questionTypeOrderNums.add(questionTypeOrderNum);
        }
        //封装成RandomPaperDTO.QuestionTypeOrderNum
        return questionTypeOrderNums;
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/3/25
     * @Description 用户考试界面查询试卷题目
     * @Param [examPaperId, questionTypeMaps]
     * @Return java.util.List<com.bosssoft.boss_exam_db.model.DTO.RandomPaperDTO.QuestionTypeOrderNum>
     * @Exception //无
     * @since JDK 1.8
     **/
    @Override
    public List<RandomPaperDTO.QuestionTypeOrderNum> queryExamPaperQuestionDetail(String examPaperId,List<Map<String, Object>> questionTypeMaps) {
        return this.queryExamPaperQuestionDetail("",examPaperId,questionTypeMaps);
    }

    /***
     * @Author lys(cherish)
     * @Phone 17720799636
     * @Date  2019/4/8
     * @Description 根据考试ID查询试卷
     * @Param [examId] 考试ID
     * @Return java.util.List<com.bosssoft.boss_exam_db.entity.ExamExamPaper>
     * @Exception
     * @since JDK 1.8
     **/
    @Override
    public List<ExamExamPaper> queryExamPaperByExamId(String examId) {
        List<ExamExamPaper> examExamPapers = examExamPaperService.queryExamPaperByExamId(examId);
        return examExamPapers;
    }
}
